package me.seu.demo.service.impl;

import lombok.extern.slf4j.Slf4j;
import me.seu.demo.dao.PictureRepository;
import me.seu.demo.model.Picture;
import me.seu.demo.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Picture文档操作接口实现
 *
 * @author liangfeihu
 * @since 2020/4/27 19:14
 */
@Slf4j
@Service("pictureService")
public class PictureServiceImpl implements PictureService {

    @Autowired
    private PictureRepository pictureRepository;

    @Override
    public List<Picture> getPicList(int current, int rowCount, String sortId) {
        PageRequest pr = null;
        if ("asc".equals(sortId)) {
            pr = PageRequest.of(--current, rowCount, Direction.ASC, "id");
        } else if ("desc".equals(sortId)) {
            pr = PageRequest.of(--current, rowCount, Direction.DESC, "id");
        } else {
            pr = PageRequest.of(--current, rowCount);
        }
        Page<Picture> page = pictureRepository.findAll(pr);
        return page.getContent();
    }

    @Override
    public Picture getPictureById(String id) {
        Optional<Picture> optional = pictureRepository.findById(id);
        return optional.isPresent() ? optional.get() : null;
    }

    @Override
    public int getPictureNum() {
        return (int) pictureRepository.count();
    }

    @Override
    public void deletePicture(String id) {
        log.info("[deletePicture] id = {}", id);
        Picture pic = getPictureById(id);
        if (pic != null) {
            pictureRepository.delete(pic);
        }
    }

    @Override
    public void saveOrUpdatePicture(Picture p) {
        log.info("[saveOrUpdatePicture] before = {}", p.toString());
        Picture save = pictureRepository.save(p);
        log.info("[saveOrUpdatePicture] return = {}", save.toString());
    }

    @Override
    public List<Picture> getSearchResult(int current, int rowCount,
                                         String sortId, String search) {
        PageRequest pr = null;
        if ("asc".equals(sortId)) {
            pr = PageRequest.of(--current, rowCount, Direction.ASC, "id");
        } else if ("desc".equals(sortId)) {
            pr = PageRequest.of(--current, rowCount, Direction.DESC, "id");
        } else {
            pr = PageRequest.of(--current, rowCount);
        }
        Page<Picture> page = pictureRepository.findByFilenameContaining(search, pr);
        return page.getContent();
    }

    @Override
    public int getSearchResultTotal(String search) {
        List<Picture> list = pictureRepository.findByFilenameContaining(search);
        return list.size();
    }

}
